﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlExtractor.Config;
using System.Xml.Linq;
//using log4net;
using System.Text.RegularExpressions;
namespace HtmlExtractor.Config
{
    public class LinqPageConfigCreater
    {
       // private readonly ILog log = LogManager.GetLogger(typeof(LinqPageConfigCreater));
        private string configPath = "";       
        public string ConfigPath
        {
            get { return configPath; }
            set { configPath = value; }
        }
        public LinqPageConfigCreater(string configPath)
        {
            
            ConfigPath = configPath;
            
        }
       
        private void ValidConfigPath(string configPath)
        {
            if (string.IsNullOrEmpty(configPath))
                throw new ConfigException("路径不正确");
        }
       
        
        #region IRuleCreater 成员

        public bool TryCreatePageConfig(string parseUri, out PageConfig pageConfig)
        {  
            ValidConfigPath(configPath);
            XElement xdoc = XElement.Load(configPath);
            pageConfig = null;
            var pageNode =xdoc.Elements("PageRule").FirstOrDefault(e => SegmentRegex.IsMatch(parseUri, (string)e.Element("TargetUri"), RegexOptions.IgnoreCase));   
            if (null != pageNode)
            {
                pageConfig = new PageConfig(pageNode);
                return true;
            }            
            return false;
        }

        

        #endregion
    }
}
